﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

namespace PictureProcessing
{
    public class PictureManager
    {
        public delegate void ImageTransformationHandler(Stream stream, int width, int height, string path);
        public static void ScaleImageDisproportional(Stream stream, int width, int height, string path)
        {
            Bitmap imgBitmap = new Bitmap(stream);
            TransformAndSave(imgBitmap, width, height, imgBitmap.RawFormat, path);
        }
        public static void ScaleImageCrop(Stream stream, int width, int height, string path)
        {
            Bitmap original = new Bitmap(stream);
            Bitmap imgBitmap = CroupImage(original, width, height);
            TransformAndSave(imgBitmap, width, height, original.RawFormat, path);
        }
        private static Bitmap CroupImage(Bitmap originalBitmap, int width, int height)
        {
            int cutWidth = originalBitmap.Width;
            int cutHeight = originalBitmap.Height;

            float proportions = (float)width / height;
            float originalBitmapProportions = (float)originalBitmap.Width / originalBitmap.Height;

            if (originalBitmapProportions > proportions)
            {
                //cut by width
                cutWidth = (int)(originalBitmap.Width * proportions / originalBitmapProportions);
            }
            else
            {
                //cut by height
                cutHeight = (int)(originalBitmap.Height / proportions * originalBitmapProportions);
            }
            if ((cutWidth == width) && (cutHeight == height))
                return originalBitmap;
            Bitmap cutted = originalBitmap.Clone(new Rectangle(0, 0, cutWidth, cutHeight), originalBitmap.PixelFormat);
            return cutted;
        }
        private static void TransformAndSave(Bitmap fromBitmap, int width, int height, ImageFormat imgFromat, String path)
        {
            if ((width == fromBitmap.Width) && (height == fromBitmap.Height))
            {
                fromBitmap.Save(path);
                return;
            }
            Bitmap result = new Bitmap(fromBitmap, width, height);
            result.Save(path, imgFromat);
        }

    }
}
